package com.huafeng.context;

import com.huafeng.answer.Answer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 花风
 * @date 2023/4/11 11:37
 * @Description 回复上下文
 */
@Component
public class AnswerContext implements BeanFactoryPostProcessor {
    public static final Map<String, Answer> map = new HashMap<>();
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //在容器中获取标有@Answer注解的
        Map<String, Object> beans = configurableListableBeanFactory.getBeansWithAnnotation(com.huafeng.annotations.Answer.class);
        Optional.ofNullable(beans).orElse(beans).forEach((type, bean) -> {
            Class<?> aClass = bean.getClass();
            com.huafeng.annotations.Answer answer = aClass.getAnnotation(com.huafeng.annotations.Answer.class);
            map.putIfAbsent(answer.type(),(Answer) bean);
        });
    }

    public static Answer get(String type){
        Answer answer = map.get(type);
        if (answer == null){
            throw new NullPointerException("answer is ");
        }
        return answer;
    }
}
